package com.lingnan.gatewayserver.filter;

import com.lingnan.gatewayserver.utils.JWTUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    // 放行的路径列表（建议使用常量或配置文件）
    private static final String[] EXCLUDE_PATHS = {
            "/admin-server/login",      //管理员登录接口
            "/admin-server/verify",     //管理员验证接口
            "/user-server/login",          // 登录接口
            "/user-server/addUser",       // 注册接口（如果有）
            "/swagger-ui/**",       // Swagger
            "/v3/api-docs/**"       // OpenAPI
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前请求路径
        String path = exchange.getRequest().getURI().getPath();

        // 检查是否为放行路径
        for (String excludePath : EXCLUDE_PATHS) {
            if (pathMatches(path, excludePath)) {
                return chain.filter(exchange); // 直接放行
            }
        }

        // 非放行路径需要验证Token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");

        if (token == null || !JWTUtil.verify(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }

    // 路径匹配方法（支持通配符）
    private boolean pathMatches(String requestPath, String pattern) {
        // 简单实现：完全匹配或通配符匹配
        if (pattern.endsWith("/**")) {
            String basePath = pattern.substring(0, pattern.length() - 3);
            return requestPath.startsWith(basePath);
        }
        return requestPath.equals(pattern);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}